#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
use strict;
use CGI qw(param);
use SIM_settings;
use SIM_base;
use SIM_cgi;
use SIM_nodeInfo;
use SIM_updateInfo;
use SIM_cgiSettings;
use SIM_report;


# Startupscript casetool, part of Sipman.

my $tool = $ARGV[0];
my $action = $ARGV[1];
my $option1 = $ARGV[2];
if ( "$option1" eq "none" ) {
  $option1 = "";
}
my $option2 = $ARGV[3];
my $option3 = $ARGV[4];
my $option4 = $ARGV[5];
my $option5 = $ARGV[6];
my $option6 = $ARGV[7];
my $option7 = $ARGV[8];

#print("tool=$tool, action=$action, option1=$option1, option2=$option2 option3=$option3 option4=$option4<BR>");

my $httpReF = $ENV{'HTTP_REFERER'};
my $httpScriptName = $ENV{'httpScriptName'};
my $systemHtml = $ENV{'SIM_SYSTEM'} || die "Oops no env found for SIM_SYSTEM.";
my $subnetDir = $SIMparam{'SIMsubnetDir'};

# read nodetype colors (for later reference)
my @rangeInfo = ();


# ----------------------------------- subs ---------------------------------------------------
# stuff imported from krischan at jodies.cx 
sub dqtobin {
        my @dq;
        my $q;
        my $i;
        my $bin;

        foreach $q (split /\./,$_[0]) {
                push @dq,$q;
        }
        for ($i = 0; $i < 4 ; $i++) {
                if (! defined $dq[$i]) {
                        push @dq,0;
                }
        }
        $bin    = pack("CCCC",@dq);      # 4 unsigned chars
        return $bin;
}

sub bintodq {
        my $dq = join ".",unpack("CCCC",$_[0]);
print
        return $dq;
}

# ---------------------------------- sipman stuff ---------------------------------------------


sub shortIp {
  my $ipAddr = "@_[0]";
# print("$ipAddr ");
  my @ips = split('\.', $ipAddr);
  my @sIp = ();
  foreach my $entry (@ips) {
    $entry =~ s/^0*//g;
    if ( "$entry" eq "" ) { $entry = "0"; }
#   print("$entry;");
    push( @sIp, $entry );
  }
  my $return = join('.', @sIp);
  return $return;
}

sub testBetween {
  my $ipAddr = "@_[0]";
  my $start = "@_[1]";
  my $stop = "@_[2]";
  my $result = "";
  my @ipTest = split('\.', $ipAddr);
  my @ipStart = split('\.', $start);
  my @ipStop = split('\.', $stop);
  foreach my $item (0 .. 3) {
    printDebug("1", " item=$item ipTest=$ipTest[$item]. ipStart=$ipStart[$item]. ipStop=$ipStop[$item].");
    if (( $ipTest[$item] < $ipStart[$item] ) or ( $ipTest[$item] > $ipStop[$item] )) {
      printDebug("1" , "testBetween: break item=$item ipTest=$ipTest[$item]. ipStart=$ipStart[$item]. ipStop=$ipStop[$item].");
      last;
    } elsif (( $ipTest[$item] > $ipStart[$item] ) or ( $ipTest[$item] < $ipStop[$item] )) {
      printDebug("1" , "testBetween: range item=$item ipTest=$ipTest[$item]. ipStart=$ipStart[$item]. ipStop=$ipStop[$item].");
      $result = "xxxx";
      last;
    } else {
      $result = "x$result";
    }
  }
  return $result;
}


sub displayNodeLine {
  my $option = "@_[0]";
  my $lineInfo = "@_[1]";
  my ( $rangeName, $type, $start, $stop, $dnsPrefix, $recOption );
  if ( $lineInfo ne "New" ) {
    ( $type, $start, $stop, $dnsPrefix, $recOption ) = split(' ', $lineInfo);
    $rangeName = longIp($start);
  } else {
    ( $start, $stop, $dnsPrefix, $recOption ) = "";
    $type = "New";
    $rangeName = "New";
  }
  
  
  $start = shortIp( $start );
  $stop = shortIp( $stop );
  if (( "$option" eq "updateEntry" ) and ( $type ne "" )) {
    print("<TR><TD></TD><TD BGCOLOR=$typeColor{$type}>
           <SELECT NAME=nodetype-$rangeName SIZE=1>\n<OPTION VALUE=$type>$type</OPTION>\n");
    while ( my ($key, $value) = each(%typeColor) ) {
      # don't allow New and unk to be selected (special types).
      if (( "$key" ne "New" ) and ( "$key" ne "unk" )) {
        print("<OPTION VALUE=$key>$key</OPTION>\n");
      }
    }
    my $recOptionCheck = "";
    if ( $recOption eq "default" ) {
      $recOptionCheck = "checked";
    }
    print("<OPTION VALUE=delete>delete</OPTION>
           </SELECT></TD>\n<TD BGCOLOR=$typeColor{$type}>
               <INPUT TYPE=text NAME=start-$rangeName VALUE=\"$start\" SIZE=15>
             </TD><TD BGCOLOR=$typeColor{$type}>
               <INPUT TYPE=text NAME=stop-$rangeName VALUE=\"$stop\" SIZE=15>
             </TD><TD BGCOLOR=$typeColor{$type}>
               <INPUT TYPE=text NAME=dnsPrefix-$rangeName VALUE=\"$dnsPrefix\" SIZE=15>
             </TD><TD BGCOLOR=$typeColor{$type}>
               <INPUT TYPE=radio NAME=recOption VALUE=\"$type\" $recOptionCheck>
             </TD></TR>\n");
  } else {
    print("<TR><TD></TD>
            <TD BGCOLOR=$typeColor{$type}>$type</TD>
            <TD BGCOLOR=$typeColor{$type}>$start</TD>
            <TD BGCOLOR=$typeColor{$type}>$stop</TD>
            <TD BGCOLOR=$typeColor{$type}>$dnsPrefix</TD>
            <TD>$recOption</TD></TR>");
  }
}

sub calcNewIp {
  my $param1 = "@_[0]";
  my $param2 = "@_[1]";
  my @result;
  my @ip1 = split('\.', $param1);
  my @ip2 = split('\.', $param2);
  foreach my $entry ( 0 .. 3 ) {
    $result[$entry] = $ip1[$entry] + $ip2[$entry];
  }
  my $return = join('.', @result);
# print("calcNewIp $param1 + $param2 = $return<BR>");
  return($return);
}

sub testIntInfo {
  # sub to import info from an external interface.
  my $intIp = $_[0];
  my $devIp = $_[1];
  my $ipDir = &getIpDir($devIp);
  my $firstMac = catFileLine("$ipDir/firstmac.txt");
# print("firstMac=$firstMac. ");
  my $longIntIp = &longIp($intIp);
  my $intInfo = catFileLine("$SIMparam{'SIMmacDatab'}/$firstMac/ipint-$longIntIp.txt");
# print("intInfo=$intInfo. ");
  my ( $ipAddr, $netmask, $intNum, $intName, $descr, $rest ) = split(' </TD><TD> ', $intInfo);
  return( $netmask, $intName, $descr);
}

sub addSubnet {
  my $ipAddr = param('ipAddr');
  my $subnet = param('subnet');
  # stuff for import from existing interface.
  my ( $netMask, $shortDescr, $longDesr );
  my $devIp = $_[1];
# printDebug(0, "ipAddr=$ipAddr, subnet=$subnet, devIp=$devIp.");
  if ( $devIp ne "none" ) {
    $ipAddr = $_[0];
    ( $netMask, $shortDescr, $longDesr ) = &testIntInfo( $ipAddr, $devIp );
#   print("$netMask, $shortDescr, $longDesr. ");
  }
  my $testResult = testIfIp($ipAddr);
  if ( ! -d $SIMparam{'SIMsubnetTemplateDir'} ) {
    print("OOps, no template directory found.");
  } elsif (( $testResult ne "oke" ) or ( $subnet eq "" )) {
#   printDebug(0, "testResult=$testResult, subnet=$subnet, ipAddr=$ipAddr.");
    print("<FORM method=post Action=$httpScriptName?$tool+addSubnet+$ipAddr+$devIp><TABLE>
             <TR><TD>Subnet address</TD><TD><INPUT NAME=ipAddr SIZE=15 TYPE=text VALUE=$ipAddr></TD></TR>
             <TR><TD>Subnet template</TD><TD><SELECT NAME=subnet SIZE=1>");
    chdir( $SIMparam{'SIMsubnetTemplateDir'} );
    my @fileList = <*>;
    foreach my $entry (@fileList) {
      if ( $netMask ne "" ) {
        open( FILE, $entry) or die "Oops, could not read $entry";
        my @config = <FILE>;
        close FILE;
        my @result = grep("NETWORK:", @config);
        my ( $descr, $net, $mask, $rest ) = split(' ', $result[0]);
#       print("<OPTION VALUE=aaa>descr=$descr, mask=$mask</OPTION>");
        if ( $mask eq $netMask ) {
          print("<OPTION VALUE=$entry>$entry</OPTION>");
        }
      } else {
        print("<OPTION VALUE=$entry>$entry</OPTION>");
      }
    }
    print("</SELECT></TABLE><INPUT TYPE=submit VALUE=\"Add subnet\" /></FORM>");
  } else {
    print("Adding subnet $ipAddr with template $subnet.<HR>");
    open(INFO, "$SIMparam{'SIMsubnetTemplateDir'}/$subnet") || die ("Oops, could not open template file $subnet.");
    my @info = <INFO>;
    close INFO;
    # test subnet;
    foreach my $regel (@info) {
      my ( $type, $subnet, $mask, $broadcast ) = split(' ', $regel);
      if ( "$type" eq "NETWORK:" ) {
        my $testSubnet = &calcIpNet( $ipAddr, $mask );
        if ( $testSubnet ne $ipAddr ) {
          print("Subnet recalculated to $testSubnet.<BR>");
          $ipAddr = $testSubnet;
        }
        last;
      }
    }
    my $longSubnet = longIp($ipAddr);
    my $subnetFile = "$SIMparam{'SIMsubnetDir'}/net-$longSubnet";
    if ( -f $subnetFile ) {
      print("Subnet definition for $ipAddr already present.<HR>");
      &listEntries;
    } else {
      open(OUT, ">$SIMparam{'SIMsubnetDir'}/net-$longSubnet") || die ("Oops, could not open subnet file net-$longSubnet.");
#     my @fileInfo = <INFO>;
      foreach my $regel (@info) {
        chomp( $regel );
        my ( $type, $rest ) = split(' ', $regel, 2);
#       print(" $type ==&gt; $rest<BR>");
        if ( "$type" eq "NAME:" ) {
          print OUT ("NAME: $rest\n");
        } elsif ( "$type" eq "NETWORK:" ) {
          my ( $subnet, $mask, $broadcast ) = split(' ', $rest);
          my $testSubnet = &calcIpNet( $ipAddr, $mask );
          if ( $testSubnet ne $ipAddr ) {
            print("<FONT SIZE+2><B>Subnet recalculated to $testSubnet.</B></FONT><BR>");
            $ipAddr = $testSubnet;
          }
          my $newBroadcast = calcNewIp( $ipAddr, $broadcast );
          print OUT ("NETWORK: $ipAddr $mask $newBroadcast\n");
        } elsif ( "$type" eq "RANGE:" ) {
          my ( $type, $start, $stop, $rest ) = split(' ', $rest);
          my $newStart = calcNewIp( $ipAddr, $start );
          my $newStop = calcNewIp( $ipAddr, $stop );
          print OUT ("RANGE: $type $newStart $newStop $rest\n");
        } elsif ( "$type" eq "OPTION:" ) {
          my ( $optionType, $rest ) = split(' ', $rest, 2);
          if ( $optionType eq "routers" ) {
            $rest = calcNewIp( $ipAddr, $rest );
          }
          print OUT ("OPTION: $optionType $rest\n");
        } elsif ( "$type" eq "DHCP:" ) {
          my ( $server, $start, $stop ) = split(' ', $rest);
          my $newStart = calcNewIp( $ipAddr, $start );
          my $newStop = calcNewIp( $ipAddr, $stop );
          print OUT ("DHCP: $server $newStart $newStop\n");
        }
      }
      close(OUT);
      &displayEntry("net-$longSubnet", "updateEntry", $shortDescr, $longDesr);
    }
  }
# print("<HR>");
}

sub displayEntry {
  my $subNet = "@_[0]";
  my $option = "@_[1]";
  my $iShortName = $_[2];
  my $iName = $_[3];
# print("subNet=$subNet option=$option....\n");
  open(INFO, "$subnetDir/$subNet") || die ("Oops, no directory entry found for $subNet.");
  my ( $network, $mask, $broadcast, $rest, $last, $name, $description, $shortName );
  my %rangeInfo = "";
  my %optionInfo = "";
  my %dhcpInfo = "";
  # get parameters from info file.
  while (my $regel = <INFO>) {
    chomp( $regel );
    my ( $type, $rest ) = split(' ', $regel, 2);
    if ( "$type" eq "NETWORK:" ) {
      ( $network, $mask, $broadcast ) = split(' ', $rest);
    } elsif ( "$type" eq "SHORTNAME:" ) {
      $shortName = $rest;
    } elsif ( "$type" eq "NAME:" ) {
      $name = $rest;
    } elsif ( "$type" eq "DESCRIPTION:" ) {
      $description = $rest;
    } elsif ( "$type" eq "RANGE:" ) {
      my ( $type, $range, $rest ) = split(' ', $rest, 3);
#     my $rangeString = longIp($range) . "-$type";
      my $rangeString = longIp($range);
#     print(" $rangeString ");
      $rangeInfo{ $rangeString } = "$type $range $rest";
    } elsif ( "$type" eq "OPTION:" ) {
      my ( $type, $options ) = split(' ', $rest, 2);
      $optionInfo{ $type } = "$type $options";
    } elsif ( "$type" eq "DHCP:" ) {
      my ( $server, $options ) = split(' ', $rest, 2);
      $dhcpInfo{ $server } = $options;
    }
  }
  close(INFO);
  # save new data
  my $rangeName =  param('netName');
  if ( $rangeName ne "" ) {
    $name = $rangeName;
    print("Updating data for $rangeName.");
    open(INFO, ">$subnetDir/$subNet") || die ("Oops, cannot write info for $subNet.");;
    print INFO ("NAME: $rangeName\n");
    $shortName = param('shortName');
    print INFO ("SHORTNAME: $shortName\n");
    $description = param('description');
    $description =~s/\r\n/<BR>/g;
    print INFO ("DESCRIPTION: $description\n");
    my $netInfo = param('netInfo');
    print INFO ("NETWORK: $netInfo\n");
    my $recOption = param('recOption');
    foreach my $key (sort keys %rangeInfo) {
      if ( "$key" ne "" ) {
#       $key = longIp($key);
#       my ( $key, $rest ) = split('-', $key);
#       $key = shortIp($key);
        my $nodetype =  param("nodetype-$key");
        my $start =  param("start-$key");
        my $stop =  param("stop-$key");
        my $dnsPrefix =  param("dnsPrefix-$key");
#       print("<BR>key: $key $nodetype, $start, $stop, $dnsPrefix...<BR>");
        # if the page is possibly updated, use this info.
        if ( $nodetype ne "" ) {
          # remove the old info and instert new info.
          delete $rangeInfo{$key};
          $rangeInfo{$key} = "$nodetype $start $stop $dnsPrefix";
        }
        if ( $nodetype eq "delete" ) {
          print("Removing range nodetype:$nodetype, start:$start, stop:$stop, dnsPrefix:$dnsPrefix...<BR>");
          delete($rangeInfo{$key});
        } elsif (( $nodetype ne "" ) and ( $start ne "" ) and ( $stop ne "" ) and ( $dnsPrefix ne "" )) {
          print INFO ("RANGE: $rangeInfo{$key}\n");
        } else {
          # remove invalid info
          print("Skipping range nodetype:$nodetype, start:$start, stop:$stop, dnsPrefix:$dnsPrefix...<BR>");
          delete($rangeInfo{$key});
        }
      }
    }
    my $nodetypeNew = param('nodetype-New');
    my $startNew = param('start-New');
    my $stopNew = param('stop-New');
    my $dnsPrefixNew = param('dnsPrefix-New');
    if ( $nodetypeNew ne "New" ) {
      my $longStart = longIp($startNew);
      if (( $startNew eq "" ) and ( $stopNew eq "" ) and ( $dnsPrefixNew eq "" )) {
        print("Not adding the new range, define all variables...");
      } elsif (( $startNew ne "" ) and ( $stopNew ne "" ) and ( $dnsPrefixNew ne "" )) {
        print("Adding the new range...");
#       $rangeInfo{ "$longStart-$rangeName" } = "$nodetypeNew $startNew $stopNew $dnsPrefixNew";
        $rangeInfo{ "$longStart" } = "$nodetypeNew $startNew $stopNew $dnsPrefixNew";
        print INFO ("RANGE: $rangeInfo{$longStart}\n");
      }
    } else {
      print("Not adding the new range, still set to New.<BR>");
    }
    foreach my $key (sort keys %optionInfo) {
      if ( "$key" ne "" ) {
        print INFO ("OPTION: $optionInfo{$key}\n");
      }
    }
    foreach my $key (sort keys %dhcpInfo) {
      if ( "$key" ne "" ) {
        print INFO ("DHCP: $key $dhcpInfo{ $key }\n");
      }
    }
    close(INFO);
    close(OUT);
  }
  if (( "$option" ne "" ) and ( "$option" ne "details" )) {
    print("<TABLE>");
  }
  if ( "$option" eq "updateEntry" ) {
  if ( $iShortName ne "" ) {
    $name = $iName;
    $shortName = $iShortName;
  }

    print("<FORM method=post Action=$httpScriptName?$tool+updateSubnet+$subNet>
            <INPUT TYPE=hidden NAME=netInfo VALUE=\"$network $mask $broadcast\">
           <TR><TD>Shortname:<INPUT TYPE=text NAME=\"shortName\" VALUE=\"$shortName\" SIZE=40></TD></TR>
           <TR><TD>Name:<INPUT TYPE=text NAME=\"netName\" VALUE=\"$name\" SIZE=60></TD>");
  } else {
    print("<TR><TD BGCOLOR=#BBBBFF>$shortName</TD><TD BGCOLOR=#BBBBFF>$name</TD>");
  }
  print("<TD>$network</TD><TD>$mask</TD><TD>$broadcast");
  if ( "$option" eq "" ) {
    printEntry2("(*)","list subnet", "$tool+listNodes", "$tool+listNodes", $subNet, "line", "</TD><TD>", "");
    print("</TD></TR>\n");
  } elsif (( "$option" eq "displayEntry" ) or ( "$option" eq "updateEntry" ) or ( "$option" eq "details" )) {
    print("</TD></TR>\n");
    print("<TR BGCOLOR=#EEEEEE><TD VALIGN=top>Description</TD><TD COLSPAN=9>");
    if ( $option eq "updateEntry" ) {
      $description =~s/<BR>/\r/g;
      print("<TEXTAREA NAME=description COLS=60 ROWS=5>$description</TEXTAREA>");
    } else {
      print("$description");
    }
    print("</TD></TR>");
    print("<TR BGCOLOR=#DDDDFF><TD>Ranges</TD><TD>type</TD><TD>start</TD><TD>stop</TD><TD>prefix</TD><TD>default</TD></TR>");
    foreach my $key (sort keys %rangeInfo) {
      if ( "$key" ne "" ) {
#       print("<TR><TD COLSPAN=9>key=$key</TD></TR>");
        displayNodeLine( $option, $rangeInfo{$key} );
      }
    }
    displayNodeLine( $option, "New");
    print("<TR BGCOLOR=#DDDDFF><TD>Options</TD><TD>type</TD><TD COLSPAN=4>settings</TD></TR>");
    foreach my $key (sort keys %optionInfo) {
      if ( "$key" ne "" ) {
        my ( $type, $options ) = split(' ', $optionInfo{$key}, 2);
        print("<TR><TD></TD><TD>$type</TD><TD>$options</TD></TR>");
      }

    }
    if ( $option ne "details" ) {
      print("</TABLE>");
    }
    if ( "$option" eq "updateEntry" ) {
      print("<INPUT TYPE=submit VALUE=\"Update info\" /></FORM>");
    }
  }
}

sub listEntries {
  my $option = "@_[0]";
  chdir $subnetDir;
  my $count = 0;
  my %subnetList = ();
  if ( -f $SIMparam{'SIMipRangeInfo'} ) {
    #build range info to add to the hash
    open ( IN, $SIMparam{'SIMipRangeInfo'} );
    my @rangeData = <IN>;
    close IN;
    foreach my $entry (@rangeData) {
      my ( $range, $start, $stop, $info ) = split(' ', $entry, 4);
      if ( $range eq "range") {
        my $longStart = &longIp($start);
        my $longStop = &longIp($stop);
        $subnetList{"$longStart $longStop"} = "$entry";
      }
    }
  } else {
    print("No Range info defined in ipRangeInfo");
  }
  my @dirList = <*>;
  print("<TABLE>
           <TR BGCOLOR=#DDDDFF>
             <TD>Name</TD>
             <TD COLSPAN=20>Info</TD>
           </TR>");
  foreach my $entry (@dirList) {
    my ( $net, $longIp ) = split('-', $entry);
    $subnetList{"$longIp $net"} = "subnet $entry";
  }
  foreach my $key (sort (keys(%subnetList))) {
    my ( $type, $rest ) = split(' ', $subnetList{$key}, 2);
    if ( $type eq "range" ) {
      my ( $start, $stop, $description ) = split(' ', $rest, 3);
      print("<TR BGCOLOR=#DDDDFF><TD COLSPAN=2>$description</TD><TD>$start</TD><TD></TD><TD>$stop</TD></TR>\n");
    } elsif ( $type eq "subnet" ) {
      displayEntry( $rest, $option );
      $count++;
    }
  }
  print("</TABLE>");
  if ( $count eq 0 ) {
    print(" No subnet definitions defined.");
  }
}

sub removeSubnet {
  my $option = "@_[0]";
  chdir $subnetDir;
  if ( -f "$subnetDir/$option" ) {
    print("Removing subnet definitions for: $option");
    system(" rm -f $subnetDir/$option ");
    if ( ! -f "$subnetDir/$option" ) {
      print(", done...");
    } else {
      print(", oops, problems removing entry.");
    }
    print("<HR>");
  }
  listEntries;
}

sub testNodeType {
  my $ipAddr = "@_[0]";
  my $nodeType = "@_[1]";
  if ( $nodeType eq "" ) {
    foreach my $entry (@rangeInfo) {
      my ( $type, $start, $stop ) = split(' ', $entry);
      my $test = testBetween( $ipAddr, $start, $stop );
      if ( $test eq "xxxx" ) {
        $nodeType = $type;
        last;
      }
    }
  }
  return $nodeType;
}

sub walkRange {
  my $option = "@_[0]";
  my $begin = "@_[1]";
  my $end = "@_[2]";
  my $reportName = "@_[3]";

  while ( $begin ne $end ) {
    my @ips = split('\.', $begin);
    $ips[3] = $ips[3] + 1;
    if ( $ips[3] > 255 ) {
      $ips[2]++;
      $ips[3] = 0;
    }
    if ( $ips[2]  > 255 ) {
      $ips[1]++;
      $ips[2] = 0;
    }
    if ( $ips[1]  > 255 ) {
      $ips[0]++;
      $ips[1] = 0;
    }
    $begin = join('.', @ips);
    my $ipDir = getIpDir($begin);
    my $nodeType = catFileLine("$ipDir/nodetype.txt");
    $nodeType = testNodeType( $begin, $nodeType );

    if ( "$begin" eq "$end" ) {
      last;
    } elsif ( $option eq "listInfo" ) {
      if ( -d $ipDir ) {
#       printNodeLine( $begin );
        &processReccord( $begin, "listEntry", "line", $reportName );
      }
    } elsif ( $option eq "updateInfo" ) {
      &processReccord( $begin, "updEntry", "line", $reportName ); 
      # set the node type after the rest in case the reccord gets set to New
      my $newNodeType = param("nodeType-$begin");
      if ( $nodeType ne $newNodeType ) {
        setNodeType( $begin, $remoteUser, $newNodeType );
      }
    } elsif ( $option eq "displayInfo" ) {
      &processReccord( $begin, "dispEntry", "line", $reportName );
    }
  }
}

sub manageNodes {
  my $action =  "@_[0]";
  my $subnet =  "@_[1]";
  my $reportName =  "@_[2]";
  chdir $subnetDir;
  @rangeInfo = ();
  my ( $startSubnet, $endSubnet, $shortName, $subnetName, $description );
  open( IN, "$subnetDir/$subnet" ) || die ("Oops, no subnet definition found.");
  my @lines = <IN>;
  close(IN);
  foreach my $line (@lines) {
    my ( $type, $var1, $var2, $var3, $rest ) = split(' ', $line, 5);
    if ( $type eq "NETWORK:" ) {
      $startSubnet = $var1;
      $endSubnet = $var3;
    } elsif ( $type eq "SHORTNAME:" ) {
      $shortName = "$var1 $var2 $var3 $rest";
    } elsif ( $type eq "NAME:" ) {
      $subnetName = "$var1 $var2 $var3 $rest";
    } elsif ( $type eq "DESCRIPTION:" ) {
      $description = "$var1 $var2 $var3 $rest";
    } elsif ( $type eq "RANGE:" ) {
      push(@rangeInfo, "$var1 $var2 $var3");
    }
  }
  #testBetween
  print("<FONT SIZE=+2><B>$shortName, $subnetName</B></FONT>($startSubnet - $endSubnet)<BR>
           <TABLE><TR><TD>$description</TD></TR></TABLE>");
  # run the update only if input is from the form.
  if ( $action eq "listNodes" ) {
    if ( $reportName eq "none" ) {
      $reportName = $SIMparam{'SIMdefaultIpListReport'};
    }
#   print("reportName:$reportName");
    print("<TABLE>");
    reportHeader( $reportName );
    &walkRange( "listInfo", $startSubnet, $endSubnet, $reportName );
    reportHeader( $reportName );
    print("</TABLE>");
  } elsif ( $action eq "manageNodes" ) {
    if ( $reportName eq "none" ) {
      $reportName = $SIMparam{'SIMdefaultIpAdminReport'};
    }
    my $formInput = param('form');
    if ( "$formInput" eq "yes" ) {
      print("<B>Updating</B><BR>");
      walkRange( "updateInfo", $startSubnet, $endSubnet, $reportName );
    }
    print("<TABLE><FORM method=post Action=$httpScriptName?$tool+manageNodes+$subnet>
           <INPUT TYPE=hidden NAME=form VALUE=yes>");
    reportHeader( $reportName );
    &walkRange( "displayInfo", $startSubnet, $endSubnet, $reportName );
    reportHeader( $reportName );
    print("</TABLE><INPUT TYPE=submit VALUE=\"Update entries\" /></FORM>");  
  }
}

#-------------------------------------- Main -------------------------------------------------
if ( "$action" eq "displaySubnet" ) {
  printEntry2("Manage nodes","manage subnet", "$tool+$action", "$tool+manageNodes", $option1, "line", "", "");
  printEntry2("Update subnet","update subnet", "$tool+$action", "$tool+updateSubnet", $option1, "line", "|", "");
  printEntry2("Remove subnet","remove subnet", "$tool+$action", "$tool+removeSubnet", $option1, "line", "|", "");
} elsif ( "$action" eq "listNodes" ) {
  printEntry2("Manage nodes","manage subnet", "$tool+$action", "$tool+manageNodes", $option1, "line", "", "");
  printReportActions("$tool+$action", $option1);
  printEntry2("subnet","update subnet", "$tool+$action", "$tool+updateSubnet", $option1, "line", "| Update", "|");
} elsif ( "$action" eq "manageNodes" ) {
  printEntry2("List nodes","List subnet", "$tool+$action", "$tool+listNodes", $option1, "line", "", "");
  printReportActions("$tool+$action", $option1);
} elsif ( "$action" eq "updateSubnet" ) {
  printEntry2("Remove subnet","remove subnet", "$tool+$action", "$tool+removeSubnet", $option1, "line", "", "");
} elsif ( "$action" eq "none" ) {
  printEntry2("List details","list details", "$tool+$action", "$tool+listDetails", $option1, "line", "", "");
  printEntry2("Add subnet","add subnet", "$tool+$action", "$tool+addSubnet", $option1, "line", "|", "");
}
print("</TR></TABLE><CENTER>");
if ( ! -d $subnetDir ) {
  print("Sorry subnet directory $subnetDir not found.");
} elsif ( $action eq "displaySubnet" ) {
  displayEntry($option1, "displayEntry");
} elsif ( $action eq "updateSubnet" ) {
# print("option1=$option1, updateEntry");
  displayEntry($option1, "updateEntry");
} elsif ( $action eq "addSubnet" ) {
  addSubnet($option1, $option2);
} elsif ( $action eq "removeSubnet" ) {
  removeSubnet( $option1 );
} elsif ( $action eq "listNodes" ) {
  manageNodes( "listNodes", $option1, $option2 );
} elsif ( $action eq "manageNodes" ) {
  manageNodes( "manageNodes", $option1, $option2 );
} elsif ( $action eq "listDetails" ) {
  listEntries("details");
} elsif ( $action eq "none" ) {
  listEntries ($option1);
} else {
  print("<H2>Oops, action $action with option $option1 not coded...</H2>");
}
